package com.example.algorithm.hash;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * @author : zhy
 * @since : 2022/7/24
 * 求两个数组的交集
 */
public class Intersection {

    public int[] intersection(int[] nums1, int[] nums2) {
        int len1=nums1.length;
        int len2=nums2.length;
        if(nums1==null||nums2==null||len1==0||len2==0)
        {
            return new int[0];
        }
        HashSet<Integer> set=new HashSet<>();
        for(int i=0;i<len1;i++)
        {
            set.add(nums1[i]);
        }
        List<Integer> list= new ArrayList<>();
        for(int i=0;i<len2;i++)
        {
            if(set.contains(nums2[i]))
            {
                list.add(nums2[i]);
                set.remove(nums2[i]);
            }
        }
        return list.stream().mapToInt(x->x).toArray();

    }

    public static void main(String[] args) {
        int[] nums1 = {1,2,2,1};
        int []nums2 = {2,2};
        Intersection intersection = new Intersection();
        int[] intersection1 = intersection.intersection(nums1, nums2);
        for(int i=0;i<intersection1.length;i++)
        {
            System.out.println(intersection1[i]);
        }
    }
}
